package com.huiqiao.lesson9.aop;

import com.huiqiao.lesson9.annotation.Log;
import com.huiqiao.lesson9.controller.BaseController;
import com.huiqiao.lesson9.service.SysLogService;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
@Log4j2
public class AspectExceptionHandler {

    @Resource
    SysLogService logService;

    @Pointcut("execution(* com.huiqiao.lesson9.controller.*.*(..))")
    public void scope() {}

    /**
     * 环绕通知，拦截 controller 包下所有 public 方法
     */
    @Around("scope()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            // 继续执行目标方法
            return joinPoint.proceed();
        } catch (RuntimeException e) {
            // 只处理 RuntimeException 自身，不处理子类
            if (e.getClass().equals(RuntimeException.class)) {
                // 捕获业务异常
                log.error(e.getMessage());
                return new BaseController.AppResponse<>(500, e.getMessage(), null);
            }
            // 其他 RuntimeException 子类交给 Spring 或上层处理
            throw e;
        }
    }

    @After("@annotation(log)")
    public void after(JoinPoint joinPoint, Log log) {
        logService.addLog(log.value());
    }
}
